import { Component, OnInit } from '@angular/core'
import { Router, ActivatedRoute } from '@angular/router' //路由引入
import { JsonApiService } from 'app/core/api/json-api.service'
import { ThrowStatement } from 'typescript'
import { config } from '../../shared/smartadmin.config'

declare var $: any
@Component({
  selector: 'sa-user-page',
  templateUrl: './user-page.component.html',
  styleUrls: ['./user-page.component.css']
})
export class UserPageComponent implements OnInit {
  validatorOptions = {
    // excluded:[":disabled"],
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      userName: {
        validators: {
          notEmpty: {
            message: '请输入用户名'
          },
          stringLength: {
            max: 30,
            message: '用户名30字以内'
          },
          callback: {
            callback: function (value, validator, $field) {
              if (value) {
                var reg = /[\u4E00-\u9FA5\uF900-\uFA2D]/
                if (reg.test(value)) {
                  return {
                    valid: false,
                    message: '请注册英文账号'
                  }
                } else {
                  return true
                }
              } else {
                return true
              }
            }.bind(this)
          },
          remote: {
            message: '用户名已存在',
            url: config.BaseURL + 'user/withoutAuth/validateUserName.html'
          }
        }
      },
      password: {
        validators: {
          notEmpty: {
            message: '请输入密码'
          },
          stringLength: {
            min: 6,
            message: '密码不少于6位'
          },
          callback: {
            callback: function (value, validator, $field) {
              if (this.page.repassword) {
                if (value === this.page.repassword) {
                  return true
                } else {
                  return {
                    valid: false,
                    message: '和确认密码不一致'
                  }
                }
              } else {
                return true
              }
            }.bind(this)
          }
        }
      },
      repassword: {
        validators: {
          notEmpty: {
            message: '请输入密码'
          },
          identical: {
            field: 'password',
            message: '两次密码不一致'
          }
        }
      },
      name: {
        validators: {
          notEmpty: {
            message: '请输入真是姓名'
          },
          stringLength: {
            max: 30,
            message: '姓名30字以内'
          }
        }
      },
      userType: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择用户类型'
          }
        }
      },
      roleId: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择所属角色'
          }
        }
      },
      phone: {
        validators: {
          integer: {
            message: '请输入数字电话号码'
          }
        }
      },
      serviceEndTime: {
        validators: {
          callback: {
            callback: function (value, validator, $field) {
              if (value) {
                var isDate = common.checkDayFormat(value)
                if (!isDate) {
                  return {
                    valid: false,
                    message: '服务到期时间格式不正确...'
                  }
                } else {
                  return true
                }
              } else {
                return true
              }
            }.bind(this)
          }
        }
      }
    }
  }
  selectedCompanyName = '' //选中公司名称
  selectedCompanyId = '' //选中公司的ID
  page: any = {
    companyId: '',
    userName: '',
    password: '',
    repassword: '',
    name: '',
    roleId: '',
    description: '',
    phone: '',
    email: '',
    companyName: '',
    serviceEndTime: null,
    headPortraitPath: '',
    userType: '',
    outsourcingTeamName: '',
    outsourcingTeamId: '',
    workerType: '',
    workerState: ''
  }
  imgFileTitle: string = '点击上传'
  fileList: File = null
  roleList: any = [] //角色list
  page_title: string = '新增'
  pageType: string = 'new'
  userId = null
  submitted: boolean = false
  curPage: number = 0 //缓存页码
  userTypeList: any = '' //
  isShowTeam: boolean = true
  constructor(private router: Router, private activatedRoute: ActivatedRoute, private jsonApiService: JsonApiService) {
    activatedRoute.queryParams.subscribe(queryParams => {
      this.userId = queryParams.id
      this.pageType = queryParams.type
      this.curPage = queryParams.nowPage
    })
  }
  //公司树选中
  companySelected(data) {
    this.page.companyId = data.companyId || ''
  }
  //表单提交
  onSubmit() {
    // const roleValue = $("#roleSelect2").val();
    if (!this.page.roleId) {
      this.jsonApiService.message('请选择角色')
      return
    }
    if (this.page.outsourcingTeamId) {
      if (this.page.workerType === '') {
        this.jsonApiService.message('请选择员工类型')
        return
      }
      if (this.page.workerState != 1 && this.page.workerState != 0) {
        this.jsonApiService.message('请选择在职状态')
        return
      }
    }

    $('#userForm').bootstrapValidator('validate') //开启验证
    let isValid = $('#userForm').data('bootstrapValidator').isValid() //验证是否通过
    if (isValid) {
      this.page.serviceEndTime = $('#serviceEndTime').val()
      var reqdata = new FormData()
      var url
      if (this.pageType === 'new') {
        url = 'user/add.html'
        for (let item in this.page) {
          reqdata.append(item, this.page[item])
        }
        reqdata.append('role.id', this.page.roleId)
        reqdata.append('userTypeName', this.userTypeName)
      } else if (this.pageType === 'updata') {
        url = 'user/edit.html'
        for (let item in this.page) {
          if (item === 'password' || item === 'repassword') {
            continue
          }
          reqdata.append(item, this.page[item])
        }
        reqdata.append('role.id', this.page.roleId)
        reqdata.append('id', this.userId)
        reqdata.append('userTypeName', this.userTypeName)
      }
      this.jsonApiService.form_http(url, reqdata).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.router.navigate(['/system/user'], {
            queryParams: {
              nowPage: this.curPage
            }
          })
        }
      })
    }
  }
  //图片上传change事件
  fileChange(files: FileList) {
    this.fileList = files[0]
    const isJPG =
      this.fileList.type === 'image/jpeg' || this.fileList.type === 'image/jpg' || this.fileList.type === 'image/png'
    const isLt500KB = this.fileList.size / 1024 < 500
    if (!isJPG) {
      this.jsonApiService.message('上传图片只能是 png, jpg, jpeg 格式!')
      return
    }
    if (!isLt500KB) {
      this.jsonApiService.message('上传图片大小不能超过500KB!')
      return
    }
    var reader = new FileReader()
    reader.readAsDataURL(this.fileList)
    var that = this
    reader.onload = function (e) {
      // 图片base64化
      var newUrl = this.result
      that.page.headPortraitPath = newUrl
      if (that.page.headPortraitPath) {
        that.imgFileTitle = '点击更换'
      } else {
        that.imgFileTitle = '点击上传'
      }
    }
  }
  //返回资源列表页
  goBack() {
    this.router.navigate(['/system/user'], { queryParams: { nowPage: this.curPage } })
  }
  //初始化日期插件
  initDate() {
    common.initDatePicker('#serviceEndTime', 1)
  }
  ngOnInit() {
    this.initUserTypeList()
    System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(() => {
      System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
        this.initDate()
      })
    })
    var that = this
    //修改为拉取全部角色
    that.initAllRole().then(() => {
      that.initAllTeam().then(() => {
        if (that.pageType === 'updata') {
          that.page_title = '编辑'
          let reqdata = 'id=' + that.userId
          that.jsonApiService.http('user/userInfo.html', reqdata).subscribe(data => {
            if (data.success) {
              for (let item in that.page) {
                that.page[item] = data.data[item]
              }
              if (data.data.userType == null) {
                that.page.userType = ''
              } else {
                that.page.userType = data.data.userType
              }

              if (data.data.userTypeName) {
                that.userTypeName = data.data.userTypeName
              }
              that.page.serviceEndTime
                ? (that.page.serviceEndTime = that.page.serviceEndTime.split(' ')[0])
                : (this.page.serviceEndTime = '')
              if (that.page.companyId) {
                that.selectedCompanyName = that.page.companyName
                that.selectedCompanyId = that.page.companyId
              }
              if (data.data.roleId) {
                that.select2Role().then(() => {
                  $('#roleSelect2').val(data.data.role.name).change()
                  var str = $("<span class='select2-selection__rendered'>" + data.data.role.name + '</span>')
                  $('#select2-roleSelect2-container').empty()
                  $('#select2-roleSelect2-container').attr('title', data.data.role.name)
                  $('#select2-roleSelect2-container').prepend(str)
                })
              }

              let outsourcingTeamName = ''
              if (data.data.outsourcingTeamId) {
                outsourcingTeamName = data.data.outsourcingTeamName
                that.isShowTeam = false
              } else {
                that.isShowTeam = true
              }
              that.select2Team().then(() => {
                $('#teamSelect2').val(outsourcingTeamName).change()
                var str = $("<span class='select2-selection__rendered'>" + outsourcingTeamName + '</span>')
                $('#select2-teamSelect2-container').empty()
                $('#select2-teamSelect2-container').attr('title', outsourcingTeamName)
                $('#select2-teamSelect2-container').prepend(str)
              })

              if (data.data.workerType == null) {
                that.page.workerType = ''
              } else {
                that.page.workerType = data.data.workerType
              }

              if (data.data.workerState == null) {
                that.page.workerState = ''
              } else {
                that.page.workerState = data.data.workerState
              }
            } else {
              this.jsonApiService.message(data.message)
            }
          })
        } else {
          that.page_title = '新增'
          that.isShowTeam = true
          that.select2Role().then(() => {
            $('#roleSelect2').val('').change()
            var str = $("<span class='select2-selection__rendered'></span>")
            $('#select2-roleSelect2-container').empty()
            $('#select2-roleSelect2-container').attr('title', '')
            $('#select2-roleSelect2-container').prepend(str)
          })
          that.select2Team().then(() => {
            $('#teamSelect2').val('').change()
            var str = $("<span class='select2-selection__rendered'></span>")
            $('#select2-teamSelect2-container').empty()
            $('#select2-teamSelect2-container').attr('title', '')
            $('#select2-teamSelect2-container').prepend(str)
          })

          return
        }
      })
    })
  }

  //拉取角色数据
  initAllRole() {
    var that = this
    //修改为展示所有角色的数据
    let reqdata = 'userType=1'
    return new Promise(function (resolve, reject) {
      that.jsonApiService.http('role/roleList.html', reqdata).subscribe(data => {
        if (data.success) {
          var roleList = data.data
          var selectdata = []
          for (var i = 0; i < roleList.length; i++) {
            var obj = {
              id: roleList[i].id,
              text: roleList[i].name
            }
            selectdata[i] = obj
          }
          that.roleList = selectdata
          resolve()
        } else {
          this.jsonApiService.message(data.message)
          reject()
        }
      })
    })
  }

  //初始化select2 角色配置
  select2Role() {
    var that = this
    return new Promise(function (resolve, reject) {
      System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
        System.import('assets/js/select2-zh-CN.js').then(() => {
          $('#roleSelect2')
            .select2({
              language: 'zh-CN',
              placeholder: '请选择',
              allowClear: true,
              data: that.roleList //为Select添加数据
            })
            .on('select2:select', function (e) {
              var data = e.params.data
              $('#roleSelect2').val(data.id).change()
              that.page.roleId = data.id
              that.page.roleName = data.text
            })
          resolve()
        })
      })
    })
  }

  teamList: any = []
  //拉取实施团队数据
  initAllTeam() {
    var that = this
    // let reqdata = 'userType=1' + this.page.userType;
    let reqdata = 'userType=1'
    return new Promise(function (resolve, reject) {
      that.jsonApiService.http('user/teamTree.html', reqdata).subscribe(data => {
        if (data.length > 0) {
          var teamList = JSON.parse(JSON.stringify(data))
          var selectdata = []
          for (var i = 0; i < teamList.length; i++) {
            var obj = {
              id: teamList[i].id,
              text: teamList[i].text
            }
            selectdata[i] = obj
          }
          that.teamList = selectdata
          resolve()
        } else {
          this.jsonApiService.message('暂无实施团队数据')
          reject()
        }
      })
    })
  }
  //初始化select2 实施团队配置
  select2Team() {
    var that = this
    return new Promise(function (resolve, reject) {
      System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
        System.import('assets/js/select2-zh-CN.js').then(() => {
          $('#teamSelect2')
            .select2({
              language: 'zh-CN',
              placeholder: '请选择',
              allowClear: true,
              data: that.teamList //为Select添加数据
            })
            .on('select2:select', function (e) {
              var data = e.params.data
              $('#teamSelect2').val(data.id).change()
              that.page.outsourcingTeamId = data.id
              that.page.outsourcingTeamName = data.text
              that.isShowTeam = false
            })
          resolve()
        })
      })
    })
  }

  clearSelect2(obj) {
    this.page.roleId = ''
    obj.empty()
    obj.prepend("<option value=''>请选择</option>")
  }

  // 获取用户类型列表
  initUserTypeList() {
    this.jsonApiService.http('role/userTypeList.html', {}).subscribe(data => {
      if (data.success) {
        for (let index = 0; index < data.data.length; index++) {
          const element = data.data[index]
          element.text = element.userTypeName
          element.id = element.userType
        }
        this.userTypeList = JSON.parse(JSON.stringify(data.data))
      }
    })
  }
  userTypeName: any = ''
  typeChange(val) {
    var that = this
    that.page.userType = val
    for (let index = 0; index < that.userTypeList.length; index++) {
      const item = that.userTypeList[index]
      if (item.id == val) {
        that.userTypeName = item.text
      }
    }
  }
  delTeamSelect() {
    $('#teamSelect2').val('').change()
    var str = $("<span class='select2-selection__rendered'></span>")
    $('#select2-teamSelect2-container').empty()
    $('#select2-teamSelect2-container').attr('title', '')
    $('#select2-teamSelect2-container').prepend(str)
    this.page.outsourcingTeamId = ''
    this.page.outsourcingTeamName = ''
    this.page.workerState = ''
    this.page.workerType = ''
    this.isShowTeam = true
  }
}
